package com.mm.cloth.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;



import java.util.ArrayList;
import java.util.List;

public class MattingCanvasView extends View {

    private static final String TAG = "MattingCanvasView";

    private Bitmap originalBitmap;
    private Bitmap maskBitmap;
    private Canvas maskCanvas;
    private Paint maskPaint;
    private Paint previewPaint;
    private Paint brushPaint;
    
    private Path currentPath;
    private List<PathInfo> pathHistory;
    private int historyIndex;
    
    private float brushSize = 20f;
    private boolean isEraseMode = true;
    private RectF imageRect;
    
    private OnPreviewUpdateListener previewUpdateListener;
    
    public interface OnPreviewUpdateListener {
        void onPreviewUpdate(Bitmap bitmap);
    }
    
    private static class PathInfo {
        Path path;
        boolean isErase;
        float brushSize;
        
        PathInfo(Path path, boolean isErase, float brushSize) {
            this.path = new Path(path);
            this.isErase = isErase;
            this.brushSize = brushSize;
        }
    }
    
    public MattingCanvasView(Context context) {
        super(context);
        init(context);
    }

    public MattingCanvasView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MattingCanvasView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }
    
    private void init(Context context) {
        Log.d(TAG, "初始化MattingCanvasView...");



        pathHistory = new ArrayList<>();
        historyIndex = -1;
        imageRect = new RectF();

        // 初始化遮罩画笔 - 优化圆润度
        maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        maskPaint.setStyle(Paint.Style.STROKE);
        maskPaint.setStrokeJoin(Paint.Join.ROUND);
        maskPaint.setStrokeCap(Paint.Cap.ROUND);
        maskPaint.setDither(true);
        maskPaint.setFilterBitmap(true);

        // 初始化预览画笔
        previewPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        previewPaint.setFilterBitmap(true);

        // 初始化显示画笔 - 优化圆润度
        brushPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        brushPaint.setColor(Color.RED);
        brushPaint.setStyle(Paint.Style.STROKE);
        brushPaint.setStrokeJoin(Paint.Join.ROUND);
        brushPaint.setStrokeCap(Paint.Cap.ROUND);
        brushPaint.setStrokeWidth(2f);
        brushPaint.setDither(true);

        currentPath = new Path();

        Log.d(TAG, "MattingCanvasView初始化完成");
    }
    
    public void setImageBitmap(Bitmap bitmap) {
        if (bitmap == null) return;
        
        originalBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false);
        
        // 创建遮罩位图
        maskBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), 
                originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        maskCanvas = new Canvas(maskBitmap);
        maskCanvas.drawColor(Color.TRANSPARENT);
        
        // 计算图片在View中的显示区域
        calculateImageRect();
        
        // 清空历史记录
        pathHistory.clear();
        historyIndex = -1;
        
        invalidate();
        updatePreview();
    }
    
    private void calculateImageRect() {
        if (originalBitmap == null) return;
        
        float viewWidth = getWidth();
        float viewHeight = getHeight();
        float imageWidth = originalBitmap.getWidth();
        float imageHeight = originalBitmap.getHeight();
        
        float scale = Math.min(viewWidth / imageWidth, viewHeight / imageHeight);
        
        float scaledWidth = imageWidth * scale;
        float scaledHeight = imageHeight * scale;
        
        float left = (viewWidth - scaledWidth) / 2;
        float top = (viewHeight - scaledHeight) / 2;
        
        imageRect.set(left, top, left + scaledWidth, top + scaledHeight);
    }
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        calculateImageRect();
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        if (originalBitmap == null) {
            // 绘制提示文字
            Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            textPaint.setColor(Color.GRAY);
            textPaint.setTextSize(48f);
            textPaint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText("点击选择图片开始抠图", getWidth() / 2f, getHeight() / 2f, textPaint);
            return;
        }
        
        // 绘制原图
        canvas.drawBitmap(originalBitmap, null, imageRect, previewPaint);
        
        // 绘制遮罩效果（将白色遮罩转换为透明淡粉色显示）
        if (maskBitmap != null) {
            Paint maskDisplayPaint = new Paint();
            maskDisplayPaint.setColorFilter(new android.graphics.ColorMatrixColorFilter(new float[]{
                0, 0, 0, 0, 255,  // 红色通道：输出255（仙女粉的红色分量）
                0, 0, 0, 0, 107,  // 绿色通道：输出107（仙女粉的绿色分量）
                0, 0, 0, 0, 157,  // 蓝色通道：输出157（仙女粉的蓝色分量）
                1, 0, 0, 0, 0     // Alpha通道：保持原始Alpha
            }));
            maskDisplayPaint.setAlpha(80); // 更透明的效果 (约30%透明度)
            canvas.drawBitmap(maskBitmap, null, imageRect, maskDisplayPaint);
        }
        
        // 绘制当前路径
        if (!currentPath.isEmpty()) {
            brushPaint.setColor(isEraseMode ? 0x80FF6B9D : 0x80FF0000); // 透明仙女粉色和透明红色
            brushPaint.setStrokeWidth(brushSize * getScaleFactor());
            canvas.drawPath(currentPath, brushPaint);
        }
    }
    
    private float getScaleFactor() {
        if (originalBitmap == null) return 1f;
        return imageRect.width() / originalBitmap.getWidth();
    }
    
    private float lastX, lastY;
    private static final float TOUCH_TOLERANCE = 4;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (originalBitmap == null) return false;

        float x = event.getX();
        float y = event.getY();

        // 检查触摸点是否在图片区域内
        if (!imageRect.contains(x, y)) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                currentPath.reset();
                currentPath.moveTo(x, y);
                lastX = x;
                lastY = y;
                break;

            case MotionEvent.ACTION_MOVE:
                float dx = Math.abs(x - lastX);
                float dy = Math.abs(y - lastY);

                // 使用二次贝塞尔曲线使路径更平滑
                if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                    currentPath.quadTo(lastX, lastY, (x + lastX) / 2, (y + lastY) / 2);
                    lastX = x;
                    lastY = y;
                    invalidate();
                }
                break;

            case MotionEvent.ACTION_UP:
                currentPath.lineTo(lastX, lastY);
                // 将当前路径添加到历史记录
                addPathToHistory();
                // 应用路径到遮罩
                applyPathToMask();
                currentPath.reset();
                invalidate();
                updatePreview();
                break;
        }

        return true;
    }
    
    private void addPathToHistory() {
        // 移除当前索引之后的历史记录
        while (pathHistory.size() > historyIndex + 1) {
            pathHistory.remove(pathHistory.size() - 1);
        }
        
        // 添加新路径
        pathHistory.add(new PathInfo(currentPath, isEraseMode, brushSize));
        historyIndex++;
        
        // 限制历史记录数量
        if (pathHistory.size() > 50) {
            pathHistory.remove(0);
            historyIndex--;
        }
    }
    
    private void applyPathToMask() {
        if (maskCanvas == null) return;
        
        // 将View坐标转换为Bitmap坐标
        Path bitmapPath = convertViewPathToBitmapPath(currentPath);
        
        maskPaint.setStrokeWidth(brushSize);
        
        if (isEraseMode) {
            // 擦除模式：绘制白色不透明遮罩（用于后续抠图）
            maskPaint.setColor(Color.WHITE);
            maskPaint.setXfermode(null);
        } else {
            // 恢复模式：擦除遮罩
            maskPaint.setColor(Color.TRANSPARENT);
            maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        }
        
        maskCanvas.drawPath(bitmapPath, maskPaint);
    }
    
    private Path convertViewPathToBitmapPath(Path viewPath) {
        Path bitmapPath = new Path();
        
        float scaleX = originalBitmap.getWidth() / imageRect.width();
        float scaleY = originalBitmap.getHeight() / imageRect.height();
        
        android.graphics.Matrix matrix = new android.graphics.Matrix();
        matrix.setTranslate(-imageRect.left, -imageRect.top);
        matrix.postScale(scaleX, scaleY);
        
        viewPath.transform(matrix, bitmapPath);
        return bitmapPath;
    }
    
    public void setBrushSize(float size) {
        this.brushSize = size;
    }
    
    public void setEraseMode(boolean eraseMode) {
        this.isEraseMode = eraseMode;
    }
    
    public void undo() {
        if (historyIndex >= 0) {
            historyIndex--;
            redrawMask();
            invalidate();
            updatePreview();
        }
    }
    
    public void redo() {
        if (historyIndex < pathHistory.size() - 1) {
            historyIndex++;
            redrawMask();
            invalidate();
            updatePreview();
        }
    }
    
    public void clearMask() {
        if (maskCanvas != null) {
            maskCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
            pathHistory.clear();
            historyIndex = -1;
            invalidate();
            updatePreview();
        }
    }
    
    private void redrawMask() {
        if (maskCanvas == null) return;
        
        // 清空遮罩
        maskCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        
        // 重新绘制历史路径
        for (int i = 0; i <= historyIndex; i++) {
            PathInfo pathInfo = pathHistory.get(i);
            Path bitmapPath = convertViewPathToBitmapPath(pathInfo.path);
            
            maskPaint.setStrokeWidth(pathInfo.brushSize);
            
            if (pathInfo.isErase) {
                maskPaint.setColor(Color.WHITE);
                maskPaint.setXfermode(null);
            } else {
                maskPaint.setColor(Color.TRANSPARENT);
                maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            }
            
            maskCanvas.drawPath(bitmapPath, maskPaint);
        }
    }
    
    public Bitmap getResultBitmap() {
        if (originalBitmap == null) return null;

        // 如果没有绘制路径，直接返回原图
        if (pathHistory.isEmpty()) {
            return originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        }

        // 确保遮罩存在，如果不存在则重新创建
        if (maskBitmap == null) {
            maskBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
                    originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
            maskCanvas = new Canvas(maskBitmap);
            maskCanvas.drawColor(Color.TRANSPARENT);

            // 重新绘制所有路径到遮罩
            redrawMask();
        }

        // 创建透明背景的结果位图
        Bitmap result = Bitmap.createBitmap(originalBitmap.getWidth(),
                originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas resultCanvas = new Canvas(result);

        // 先绘制原图
        resultCanvas.drawBitmap(originalBitmap, 0, 0, null);

        // 使用DST_IN模式：只保留遮罩区域，其他区域变透明
        Paint maskApplyPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        maskApplyPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        resultCanvas.drawBitmap(maskBitmap, 0, 0, maskApplyPaint);

        return result;
    }
    
    private void updatePreview() {
        if (previewUpdateListener != null) {
            Bitmap preview = getResultBitmap();
            previewUpdateListener.onPreviewUpdate(preview);
        }
    }
    
    public void setOnPreviewUpdateListener(OnPreviewUpdateListener listener) {
        this.previewUpdateListener = listener;
    }

    public boolean hasDrawnPaths() {
        return pathHistory.size() > 0;
    }

    /**
     * 获取用于AI抠图的遮罩图像
     * @return 遮罩Bitmap，白色区域为需要保留的前景，黑色区域为需要移除的背景
     */
    public Bitmap getMaskBitmap() {
        if (originalBitmap == null) {
            Log.e(TAG, "原始图像为空，无法生成遮罩");
            return null;
        }

        if (imageRect == null) {
            Log.e(TAG, "图像矩形未初始化，无法生成遮罩");
            return null;
        }

        // 创建遮罩图像
        Bitmap maskForAI = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas maskCanvas = new Canvas(maskForAI);

        // 如果没有绘制任何路径，返回全白遮罩（保留整个图像）
        if (pathHistory.isEmpty()) {
            Log.d(TAG, "没有绘制路径，返回全白遮罩（保留整个图像）");
            maskCanvas.drawColor(Color.WHITE);
            return maskForAI;
        }

        // 初始化为全白（默认保留所有内容）
        maskCanvas.drawColor(Color.WHITE);

        // 设置绘制模式的画笔
        Paint maskPaint = new Paint();
        maskPaint.setAntiAlias(true);
        maskPaint.setStyle(Paint.Style.STROKE);
        maskPaint.setStrokeCap(Paint.Cap.ROUND);
        maskPaint.setStrokeJoin(Paint.Join.ROUND);

        // 计算坐标转换比例
        float scaleX = (float) originalBitmap.getWidth() / imageRect.width();
        float scaleY = (float) originalBitmap.getHeight() / imageRect.height();

        Log.d(TAG, "坐标转换比例 - scaleX: " + scaleX + ", scaleY: " + scaleY);
        Log.d(TAG, "图像矩形: " + imageRect.toString());
        Log.d(TAG, "原图尺寸: " + originalBitmap.getWidth() + "x" + originalBitmap.getHeight());

        // 绘制所有路径
        for (PathInfo pathInfo : pathHistory) {
            // 创建转换后的路径
            Path transformedPath = new Path();

            // 将画布坐标转换为图像坐标
            android.graphics.Matrix matrix = new android.graphics.Matrix();
            matrix.setTranslate(-imageRect.left, -imageRect.top); // 移动到原点
            matrix.postScale(scaleX, scaleY); // 缩放到图像尺寸

            pathInfo.path.transform(matrix, transformedPath);

            // 设置画笔
            maskPaint.setStrokeWidth(pathInfo.brushSize * Math.max(scaleX, scaleY));

            if (pathInfo.isErase) {
                // 擦除模式：绘制黑色（标记为背景，需要移除）
                maskPaint.setColor(Color.BLACK);
                Log.d(TAG, "绘制擦除路径（黑色）");
            } else {
                // 保留模式：绘制白色（标记为前景，需要保留）
                maskPaint.setColor(Color.WHITE);
                Log.d(TAG, "绘制保留路径（白色）");
            }

            maskCanvas.drawPath(transformedPath, maskPaint);
        }

        Log.d(TAG, "生成AI抠图遮罩完成: " + maskForAI.getWidth() + "x" + maskForAI.getHeight());
        return maskForAI;
    }

    /**
     * 获取原始的遮罩图像（用于预览）
     */
    public Bitmap getOriginalMaskBitmap() {
        return maskBitmap;
    }

    /**
     * 设置画笔模式
     * @param isErase true=擦除模式（移除背景），false=保留模式（保留前景）
     */
    public void setBrushMode(boolean isErase) {
        this.isEraseMode = isErase;
        Log.d(TAG, "画笔模式设置为: " + (isErase ? "擦除" : "保留"));
    }

    /**
     * 设置画笔大小
     * @param size 画笔大小（像素）
     */
    public void setBrushSize(int size) {
        this.brushSize = Math.max(5, Math.min(100, size)); // 限制在5-100像素之间
        Log.d(TAG, "画笔大小设置为: " + this.brushSize);
    }



    public int getPathHistorySize() {
        return pathHistory.size();
    }

    public Bitmap forceGenerateResult() {
        Log.d(TAG, "=== 开始执行抠图处理 ===");

        if (originalBitmap == null) {
            Log.e(TAG, "原始图片为空");
            return null;
        }

        // 如果没有绘制路径，返回原图
        if (pathHistory.isEmpty()) {
            Log.w(TAG, "没有绘制路径，返回原图");
            return originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        }

        // 确保遮罩存在
        if (maskBitmap == null) {
            Log.d(TAG, "创建遮罩位图");
            maskBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
                    originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
            maskCanvas = new Canvas(maskBitmap);
            maskCanvas.drawColor(Color.TRANSPARENT);
        }

        // 重新绘制所有路径到遮罩
        Log.d(TAG, "重新绘制遮罩，路径数量：" + pathHistory.size());
        redrawMask();

        // 使用CPU处理进行抠图
        Log.d(TAG, "使用CPU处理进行抠图");
        return performCPUMatting();
    }

    /**
     * CPU抠图处理（回退方案）
     */
    private Bitmap performCPUMatting() {
        Log.d(TAG, "执行CPU抠图处理");

        // 创建透明背景的结果位图
        Bitmap result = Bitmap.createBitmap(originalBitmap.getWidth(),
                originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas resultCanvas = new Canvas(result);

        // 先绘制原图
        resultCanvas.drawBitmap(originalBitmap, 0, 0, null);

        // 使用DST_IN模式：只保留遮罩区域，其他区域变透明
        Paint maskApplyPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        maskApplyPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        resultCanvas.drawBitmap(maskBitmap, 0, 0, maskApplyPaint);

        Log.d(TAG, "CPU抠图处理完成");
        return result;
    }

    /**
     * 高级抠图处理（带边缘平滑）
     */
    public Bitmap performAdvancedMatting() {
        Log.d(TAG, "=== 开始高级抠图处理 ===");

        if (originalBitmap == null || pathHistory.isEmpty()) {
            Log.w(TAG, "无法执行高级抠图：图片为空或无绘制路径");
            return forceGenerateResult();
        }

        // 确保遮罩存在
        if (maskBitmap == null) {
            maskBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
                    originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
            maskCanvas = new Canvas(maskBitmap);
            maskCanvas.drawColor(Color.TRANSPARENT);
            redrawMask();
        }

        // 使用基础抠图处理
        Log.d(TAG, "使用基础抠图处理");
        return forceGenerateResult();
    }


}
